package com.tomtop.core.dorequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tomtop.core.utils.JSONUtils;
import com.tomtop.core.utils.ObjectUtils;

public final class HttpContext {

	private final static Logger LOGGER = LoggerFactory.getLogger(HttpContext.class);

	static ThreadLocal<HttpContext> httpresponses = new ThreadLocal<HttpContext>() {
		protected HttpContext initialValue() {
			return new HttpContext();
		};
	};

	public static HttpContext getCurrentResponse() {
		return httpresponses.get();
	}

	public HttpContext() {
	}

	public HttpContext(RequestEntity<String> request, ResponseEntity<String> response) {
		this.request = request;
		this.response = response;
		httpresponses.set(this);
	}

	public HttpContext(RequestEntity<String> request, Throwable exception) {
		this.request = request;
		this.exception = exception;
		httpresponses.set(this);
	}

	private RequestEntity<String> request;
	private ResponseEntity<String> response;
	private Throwable exception;

	public static RequestEntity<String> getRequest() {
		return httpresponses.get().request;
	}

	public static ResponseEntity<String> getResponse() {
		return httpresponses.get().response;
	}

	public static Throwable getException() {
		return httpresponses.get().exception;
	}

	/**
	 * 根据响应code判断是否响应成功，只有响应码等于200时才会成功
	 * 
	 * @return
	 */
	public static boolean isOk() {
		ResponseEntity<String> response = getResponse();
		return ObjectUtils.isNotNull(() -> response, () -> response.getStatusCode())
				&& (response.getStatusCode().is1xxInformational() || response.getStatusCode().is2xxSuccessful()
						|| response.getStatusCode().is3xxRedirection());
	}

	/**
	 * 把响应结果以字符串的方式输出，
	 * 
	 * @return
	 */
	public static String getBody() {
		ResponseEntity<String> response = getResponse();
		if (ObjectUtils.isNull(() -> response) && !response.hasBody())
			return null;
		return response.getBody();
	}

	public static <T> T getBodyToObject(TypeReference<T> typereference) {
		if (isOk()) {
			String body = getBody();
			LOGGER.debug("响应报文提数据:{}", body);
			return JSONUtils.fromObject(body, typereference);
		}
		return null;
	}

	public void close() {
	}
}